package com.msb.servicepassengeruser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msb.commons.constant.CommonStatusEnum;
import com.msb.commons.dto.PassengerUser;
import com.msb.commons.response.ResponseResult;
import com.msb.servicepassengeruser.mapper.PassengerUserMapper;
import com.msb.servicepassengeruser.service.PassengerUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chshh
 * @since 2022-10-24
 */
@Service
public class PassengerUserServiceImpl extends ServiceImpl<PassengerUserMapper, PassengerUser> implements PassengerUserService {

    @Resource
    private PassengerUserMapper passengerUserMapper;

    /**
     * 登录或者注册
     * 传入手机号,查询用户信息
     * 若不存在,插入用户信息
     * @param passengerPhone
     * @return
     */
    public ResponseResult loginOrRegister(String passengerPhone){

        //根据手机号查询用户信息
        QueryWrapper<PassengerUser> w = new QueryWrapper<>();
        w.eq("passenger_phone",passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectList(w);

        //判断用户信息是否存在
        if(passengerUsers.size()==0){
            //若不存在,插入用户信息
            PassengerUser passengerUser = new PassengerUser();
            passengerUser.setPassengerPhone(passengerPhone);
            passengerUser.setPassengerName("张三");
            passengerUser.setPassengerGender((byte) 0);
            passengerUser.setState((byte) 0);
            passengerUser.setGmtCreate(LocalDateTime.now());

            passengerUserMapper.insert(passengerUser);
        }

        return ResponseResult.success();
    }

    @Override
    public ResponseResult getUserByPhone(String passengerPhone) {
        //根据手机号查询用户信息
        QueryWrapper<PassengerUser> w = new QueryWrapper<>();
        w.eq("passenger_phone",passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectList(w);

        if(passengerUsers.size()==0){
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXISTS.getCode(),CommonStatusEnum.USER_NOT_EXISTS.getValue());
        } else {
            PassengerUser passengerUser = passengerUsers.get(0);
            return ResponseResult.success(passengerUser);
        }
    }
}
